import { reqGetShopcart } from '@/api/index'
const state = {
     shopCartList: JSON.parse(sessionStorage.getItem('SHOPCARTLIST')) || []
}
const mutations = {
    setShopCart(state, newItem) {
        const index = state.shopCartList.findIndex(item => item.id === newItem.id);
        if (index !== -1) {
            // 更新已有项
            state.shopCartList.splice(index, 1, newItem);
        } else {
            // 添加新项
            state.shopCartList.push(newItem);
             // ✅ 每次修改后，同步存一份到 sessionStorage
        sessionStorage.setItem('SHOPCARTLIST', JSON.stringify(state.shopCartList))
        }
    },
    //删除某一个购物车商品
    delShopCartItem(state, delId) {
        state.shopCartList = state.shopCartList.filter(item => item.id != delId)
        console.log('打印一下删除后的购物车数据：');
        console.log(state.shopCartList);
         // ✅ 删除后也要同步更新 sessionStorage
        sessionStorage.setItem('SHOPCARTLIST', JSON.stringify(state.shopCartList))
    },
    //删除全部勾选的购物车商品
    delIscheckedCartItem(state){
        state.shopCartList=state.shopCartList.filter(item=>item.isChecked!=1)
        sessionStorage.setItem('SHOPCARTLIST',JSON.stringify(state.shopCartList))
    }
}

const actions = {
    async addOrUpdateShopCart(context, cartParams) {
        console.log(`打印一下id`);

        console.log(cartParams.id);
        //注意：async函数执行返回的结果一定是一个promise【要么成功，要么失败】
        const res = await reqGetShopcart()
        if (res.code == 200) {
            let data = res.data.data
            data = data.find(item => item.id == cartParams.id)
            console.log(data);
            const finalData = {
                ...data,
                skuNum: cartParams.num
            }
            console.log(finalData);

            context.commit('setShopCart', finalData)
        } else {
            return Promise.reject(new Error('fail'))
        }

    }
}
const getters = {}
export default {
    namespaced: true,
    state, mutations, actions, getters
}